<template>
  <div class="commission-withdraw">
    <h1 class="page-title">佣金提现</h1>

    <!-- 提现概览 -->
    <div class="overview-card">
      <div class="overview-item available">
        <div class="item-title">可提现佣金</div>
        <div class="item-value">¥{{ userDataInfo.withdraw_funds || 0 }}</div>
      </div>
      <div class="overview-item pending">
        <div class="item-title">待结算佣金</div>
        <div class="item-value">¥{{ userDataInfo.wait_money || 0 }}</div>
      </div>
      <div class="overview-item settled">
        <div class="item-title">已结算佣金</div>
        <div class="item-value">¥{{ userDataInfo.withdrawal_money || 0 }}</div>
      </div>
      <div class="overview-item fee">
        <div class="item-title">本月佣金总额</div>
        <div class="item-value">{{ userDataInfo.month_money_total || 0 }}</div>
      </div>
      <div class="overview-item fee">
        <div class="item-title">累计佣金总额</div>
        <div class="item-value">{{ userDataInfo.commission_money_total || 0 }}</div>
      </div>
    </div>

    <!-- 提现表单 -->
    <div class="withdraw-form-card">
      <h2 class="card-title">申请提现</h2>
      <form @submit.prevent="submitWithdrawal" class="withdraw-form">
        <div class="form-group">
          <label for="money">提现金额</label>
          <div class="money-input-wrapper">
            <input type="number" id="money" v-model="withdrawalForm.money" min="1" :max="overviewData.availableAmount"
              step="0.01" placeholder="最小提现金额为1元" required>
            <span class="currency-symbol">¥</span>
          </div>

          <div class="money-info">
            <span>可提金额: ¥{{ userDataInfo.withdraw_funds }}</span>
            <!-- <button type="button" class="use-max-btn" @click="useMaxAmount">全部提现</button> -->
          </div>

          <div v-if="formErrors.money" class="error-message">{{ formErrors.money }}</div>
        </div>

        <div class="form-group">
          <label for="address">地址</label>
          <div class="address-input-wrapper">
            <input type="text" id="address" v-model="withdrawalForm.address" placeholder="请输入您的地址" required>
            <!-- <button type="button" class="use-saved-btn" @click="useSavedAddress" v-if="savedAddresses.length > 0">
              使用已保存地址
            </button> -->
          </div>
          <div v-if="formErrors.address" class="error-message">{{ formErrors.address }}</div>
        </div>

        <!-- <div class="form-group">
          <label>提现明细</label>
          <div class="summary-table">
            <div class="summary-row">
              <span>提现金额</span>
              <span>¥{{ withdrawalForm.money ? parseFloat(withdrawalForm.money).toFixed(2) : '0.00' }}</span>
            </div>
            <div class="summary-row">
              <span>手续费 ({{ overviewData.withdrawalFee * 100 }}%)</span>
              <span>¥{{ calculateFee() }}</span>
            </div>
            <div class="summary-row total">
              <span>实际到账</span>
              <span>¥{{ calculateActualAmount() }}</span>
            </div>
          </div>
        </div> -->

        <div class="form-group">
          <button type="submit" class="submit-btn">
            <span v-if="submitting">处理中...</span>
            <span v-else>确认提现</span>
          </button>
        </div>
      </form>
    </div>

    <!-- 提现记录 -->
    <WithdrawalRecordsTable ref="withdrawalRecordsTableRef" />


    <!-- 提现详情弹窗 -->
    <div v-if="detailModalVisible" class="detail-modal">
      <div class="modal-backdrop" @click="detailModalVisible = false"></div>
      <div class="modal-content">
        <div class="modal-header">
          <h3>提现详情</h3>
          <button class="close-btn" @click="detailModalVisible = false">×</button>
        </div>
        <div class="modal-body">
          <div class="detail-section">
            <div class="detail-item">
              <span class="label">提现单号</span>
              <span class="value">{{ currentRecord?.id }}</span>
            </div>
            <div class="detail-item">
              <span class="label">提现金额</span>
              <span class="value">¥{{ currentRecord?.money.toFixed(2) }}</span>
            </div>

            <!-- <div class="detail-item">
              <span class="label">手续费</span>
              <span class="value">
                <template v-if="currentRecord?.fee !== null">¥{{ currentRecord?.fee.toFixed(2) }}</template>
<template v-else>-</template>
</span>
</div>
<div class="detail-item">
  <span class="label">实际到账</span>
  <span class="value">
    <template v-if="currentRecord?.actualAmount !== null">¥{{ currentRecord?.actualAmount.toFixed(2)
                  }}</template>
    <template v-else>-</template>
  </span>
</div>

<div class="detail-item">
  <span class="label">USDT地址</span>
  <span class="value address">{{ currentRecord?.address }}</span>
</div>

<div v-if="currentRecord?.rejectReason" class="detail-item">
  <span class="label">拒绝原因</span>
  <span class="value reject-reason">{{ currentRecord?.rejectReason }}</span>
</div> -->
          </div>

          <div class="timeline-section">
            <h4>处理进度</h4>
            <div class="timeline">
              <div v-for="(item, index) in currentRecord?.timeline" :key="index" class="timeline-item"
                :class="{ 'completed': true }">
                <div class="timeline-point" :class="item.status"></div>
                <div class="timeline-content">
                  <div class="timeline-date">{{ formatDateTime(item.time) }}</div>
                  <div class="timeline-description">{{ item.description }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提现成功弹窗 -->
    <div v-if="successModalVisible" class="success-modal">
      <div class="modal-backdrop" @click="successModalVisible = false"></div>
      <div class="modal-content">
        <div class="modal-header">
          <h3>提现申请已提交</h3>
          <button class="close-btn" @click="successModalVisible = false">×</button>
        </div>
        <div class="modal-body">
          <div class="success-icon">
            <i class="fas fa-check-circle"></i>
          </div>
          <p class="success-message">您的提现申请已成功提交，我们将尽快处理</p>
          <div class="success-detail">
            <div class="detail-item">
              <span class="label">提现金额</span>
              <span class="value">¥{{ lastSubmittedAmount.toFixed(2) }}</span>
            </div>
            <!-- <div class="detail-item">
              <span class="label">手续费</span>
              <span class="value">¥{{ (lastSubmittedAmount * overviewData.withdrawalFee).toFixed(2) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">实际到账</span>
              <span class="value">¥{{ (lastSubmittedAmount * (1 - overviewData.withdrawalFee)).toFixed(2) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">USDT地址</span>
              <span class="value address">{{ lastSubmittedAddress }}</span>
            </div> -->
          </div>
          <button class="close-success-btn" @click="successModalVisible = false">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { generateWithdrawalRecordsData } from '@/utils/agentMock';
import { getRegionUserDataInfoApi, SetRegionPayWithdrawal } from '@/api/index'
import { ElMessage } from 'element-plus';
import WithdrawalRecordsTable from './WithdrawalRecordsTable.vue'

// 提现概览数据
const overviewData = reactive({
  availableAmount: 5280.45,     // 可提现金额
  pendingAmount: 1624.50,       // 待结算金额
  settledAmount: 12500.78,      // 已结算金额
  withdrawalFee: 0.01           // 提现手续费率（1%）
});

// 提现表单
const withdrawalForm = reactive({
  money: '',
  address: ''
});

// 表单错误信息
const formErrors = reactive({
  money: '',
  address: ''
});

// 已保存的USDT地址
const savedAddresses = ref([
  '0x6B175474E89094C44Da98b954EedeAC495271d0F',
  '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'
]);

// 提现记录
const withdrawalRecords = ref([]);
const loading = ref(false);
const filters = reactive({
  startDate: '',
  endDate: '',
  status: ''
});

// 模态框状态
const detailModalVisible = ref(false);
const successModalVisible = ref(false);
const currentRecord = ref(null);
const submitting = ref(false);
const lastSubmittedAmount = ref(0);
const lastSubmittedAddress = ref('');

// 计算属性
const isFormValid = computed(() => {
  return withdrawalForm.money &&
    parseFloat(withdrawalForm.money) >= 100 &&
    parseFloat(withdrawalForm.money) <= overviewData.availableAmount &&
    withdrawalForm.address.trim().length > 0;
});

// 方法
const calculateFee = () => {
  if (!withdrawalForm.money) return '0.00';
  const money = parseFloat(withdrawalForm.money);
  return (money * overviewData.withdrawalFee).toFixed(2);
};

const calculateActualAmount = () => {
  if (!withdrawalForm.money) return '0.00';
  const money = parseFloat(withdrawalForm.money);
  return (money * (1 - overviewData.withdrawalFee)).toFixed(2);
};

const useMaxAmount = () => {
  withdrawalForm.money = userDataInfo.withdraw_funds.toString();
  validateAmount();
};

const useSavedAddress = () => {
  // 如果有多个地址，这里可以改为显示选择列表
  withdrawalForm.address = savedAddresses.value[0];
  validateAddress();
};

const validateAmount = () => {
  const money = parseFloat(withdrawalForm.money);
  if (!withdrawalForm.money) {
    formErrors.money = '请输入提现金额';
  } else if (money < 100) {
    formErrors.money = '最小提现金额为100元';
  } else if (money > overviewData.availableAmount) {
    formErrors.money = '提现金额不能超过可提现余额';
  } else {
    formErrors.money = '';
  }
};

const validateAddress = () => {
  const address = withdrawalForm.address.trim();
  if (!address) {
    formErrors.address = '请输入USDT地址';
  } else if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
    formErrors.address = '请输入有效的USDT地址';
  } else {
    formErrors.address = '';
  }
};

const fetchWithdrawalRecords = () => {
  loading.value = true;

  try {
    const records = generateWithdrawalRecordsData({
      startDate: filters.startDate || undefined,
      endDate: filters.endDate || undefined,
      status: filters.status || undefined
    });

    withdrawalRecords.value = records;
  } catch (error) {
    console.error('获取提现记录失败:', error);
  } finally {
    loading.value = false;
  }
};

const showRecordDetail = (record) => {
  currentRecord.value = record;
  detailModalVisible.value = true;
};

const getStatusText = (status) => {
  switch (status) {
    case 'pending': return '待处理';
    case 'processing': return '处理中';
    case 'completed': return '已完成';
    case 'rejected': return '已拒绝';
    default: return '未知状态';
  }
};

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

const formatDateTime = (dateString) => {
  const date = new Date(dateString);
  return `${formatDate(dateString)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 生命周期钩子
onMounted(() => {
  // fetchWithdrawalRecords();
  getUserDataInfoRequest()
});

// ------------------------------

const withdrawalRecordsTableRef = ref()

const submitWithdrawal = async () => {
  // 表单验证
  // validateAmount();
  // validateAddress();

  // if (formErrors.money || formErrors.address) {
  //   return;
  // }

  // 显示提交中状态
  submitting.value = true;

  try {
    const res = await SetRegionPayWithdrawal(withdrawalForm)


    // // 模拟API调用延迟
    // await new Promise(resolve => setTimeout(resolve, 1500));

    // 保存提交信息，用于成功弹窗显示
    lastSubmittedAmount.value = parseFloat(withdrawalForm.money);
    lastSubmittedAddress.value = withdrawalForm.address;

    // 重置表单
    withdrawalForm.money = '';
    withdrawalForm.address = '';

    // 模拟提现后余额减少
    overviewData.availableAmount -= lastSubmittedAmount.value;

    // 显示成功弹窗
    successModalVisible.value = true;

    getUserDataInfoRequest()

    withdrawalRecordsTableRef.value.searchTable()

    // 刷新提现记录
    fetchWithdrawalRecords();

  } catch (error) {
    console.error('提现申请提交失败:', error);
    alert('提现申请提交失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
};
const userDataInfo = ref({})

const getUserDataInfoRequest = async () => {
  try {
    const res = await getRegionUserDataInfoApi({})

    userDataInfo.value = res.data
  } catch (error) {
    console.log(error);
    ElMessage({
      type: 'error',
      message: error.msg
    })
  }
}
</script>

<style lang="scss" scoped>
.commission-withdraw {
  padding: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 24px;
    color: #333;
  }

  // 提现概览卡片
  .overview-card {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 20px;
    margin-bottom: 24px;

    @media (max-width: 1200px) {
      grid-template-columns: repeat(2, 1fr);
    }

    @media (max-width: 640px) {
      grid-template-columns: 1fr;
    }

    .overview-item {
      background-color: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      border-top: 4px solid #ccc;

      &.available {
        border-top-color: #4CAF50;
      }

      &.pending {
        border-top-color: #FF9800;
      }

      &.settled {
        border-top-color: #2196F3;
      }

      &.fee {
        border-top-color: #9C27B0;
      }

      .item-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }

      .item-value {
        font-size: 24px;
        font-weight: 600;
        color: #333;
      }
    }
  }

  // 提现表单卡片
  .withdraw-form-card {
    background-color: #fff;
    border-radius: 8px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .card-title {
      font-size: 18px;
      font-weight: 600;
      margin-top: 0;
      margin-bottom: 24px;
      color: #333;
    }

    .withdraw-form {
      .form-group {
        margin-bottom: 20px;

        label {
          display: block;
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
        }

        .money-input-wrapper,
        .address-input-wrapper {
          position: relative;

          input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            transition: border-color 0.3s;

            &:focus {
              outline: none;
              border-color: #4a6cf7;
            }
          }

          .currency-symbol {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #666;
            font-size: 16px;
          }

          input[type="number"] {
            padding-left: 32px;
          }

          .use-saved-btn {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #4a6cf7;
            font-size: 14px;
            cursor: pointer;
            padding: 4px 8px;

            &:hover {
              text-decoration: underline;
            }
          }
        }

        .money-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 8px;
          font-size: 14px;
          color: #666;

          .use-max-btn {
            background: none;
            border: none;
            color: #4a6cf7;
            font-size: 14px;
            cursor: pointer;
            padding: 4px 0;

            &:hover {
              text-decoration: underline;
            }
          }
        }

        .error-message {
          color: #f44336;
          font-size: 14px;
          margin-top: 8px;
        }

        .summary-table {
          background-color: #f9f9f9;
          border-radius: 4px;
          overflow: hidden;

          .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 12px 16px;
            border-bottom: 1px solid #eee;

            &:last-child {
              border-bottom: none;
            }

            &.total {
              font-weight: 600;
              background-color: #f5f5f5;
            }
          }
        }

        .submit-btn {
          width: 100%;
          padding: 12px 24px;
          background-color: #4a6cf7;
          color: white;
          border: none;
          border-radius: 4px;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.3s;

          &:hover {
            background-color: #3a5bd7;
          }

          &:disabled {
            background-color: #c5c5c5;
            cursor: not-allowed;
          }
        }
      }
    }
  }

  // 提现记录卡片
  .withdrawal-records-card {
    background-color: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;

      @media (max-width: 768px) {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
      }

      .card-title {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
        color: #333;
      }

      .filter-controls {
        display: flex;
        gap: 16px;

        @media (max-width: 640px) {
          flex-direction: column;
          width: 100%;
        }

        .date-filter {
          display: flex;
          align-items: center;

          .date-input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            width: 140px;

            &:focus {
              outline: none;
              border-color: #4a6cf7;
            }
          }

          .date-separator {
            margin: 0 8px;
            color: #666;
          }
        }

        .status-filter {
          padding: 8px 12px;
          border: 1px solid #ddd;
          border-radius: 4px;
          font-size: 14px;
          min-width: 120px;

          &:focus {
            outline: none;
            border-color: #4a6cf7;
          }
        }
      }
    }

    // 加载和空状态
    .loading-state,
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 48px 0;
      color: #999;

      .spinner {
        width: 40px;
        height: 40px;
        border: 4px solid rgba(74, 108, 247, 0.1);
        border-left-color: #4a6cf7;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 16px;
      }

      @keyframes spin {
        to {
          transform: rotate(360deg);
        }
      }

      i {
        font-size: 40px;
        color: #ddd;
        margin-bottom: 16px;
      }

      p {
        margin: 0;
        font-size: 16px;
      }
    }

    // 记录表格
    .records-table {
      width: 100%;
      border-collapse: collapse;

      th,
      td {
        text-align: left;
        padding: 12px 16px;
        border-bottom: 1px solid #eee;
      }

      th {
        font-weight: 600;
        color: #666;
        background-color: #f9f9f9;
        white-space: nowrap;
      }

      td {
        color: #333;
      }

      .id-cell {
        font-family: 'Courier New', monospace;
        white-space: nowrap;
      }

      .money-cell,
      .fee-cell {
        text-align: right;
      }

      .status-tag {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;

        &.status-pending {
          background-color: rgba(255, 152, 0, 0.1);
          color: #FF9800;
        }

        &.status-processing {
          background-color: rgba(33, 150, 243, 0.1);
          color: #2196F3;
        }

        &.status-completed {
          background-color: rgba(76, 175, 80, 0.1);
          color: #4CAF50;
        }

        &.status-rejected {
          background-color: rgba(244, 67, 54, 0.1);
          color: #F44336;
        }
      }

      .action-btn {
        background: none;
        border: none;
        color: #4a6cf7;
        cursor: pointer;
        font-size: 14px;

        &:hover {
          text-decoration: underline;
        }
      }

      // 响应式表格
      @media (max-width: 992px) {
        display: block;
        overflow-x: auto;
      }
    }
  }

  // 模态框样式
  .detail-modal,
  .success-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    display: flex;
    align-items: center;
    justify-content: center;

    .modal-backdrop {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
    }

    .modal-content {
      position: relative;
      background-color: #fff;
      border-radius: 8px;
      width: 90%;
      max-width: 600px;
      max-height: 90vh;
      overflow-y: auto;
      box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
      animation: modalFadeIn 0.3s;

      @keyframes modalFadeIn {
        from {
          opacity: 0;
          transform: translateY(-20px);
        }

        to {
          opacity: 1;
          transform: translateY(0);
        }
      }

      .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 24px;
        border-bottom: 1px solid #eee;

        h3 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          color: #333;
        }

        .close-btn {
          background: none;
          border: none;
          font-size: 24px;
          color: #999;
          cursor: pointer;
          padding: 0;
          line-height: 24px;

          &:hover {
            color: #666;
          }
        }
      }

      .modal-body {
        padding: 24px;
      }
    }
  }

  // 详情模态框内容
  .detail-section {
    margin-bottom: 24px;

    .detail-item {
      display: flex;
      margin-bottom: 12px;

      .label {
        min-width: 120px;
        color: #666;
      }

      .value {
        flex: 1;
        color: #333;
        word-break: break-all;

        &.address {
          font-family: 'Courier New', monospace;
          background-color: #f5f5f5;
          padding: 4px 8px;
          border-radius: 4px;
        }

        &.reject-reason {
          color: #F44336;
        }
      }
    }
  }

  .timeline-section {
    h4 {
      font-size: 16px;
      font-weight: 600;
      margin-top: 0;
      margin-bottom: 16px;
      color: #333;
    }

    .timeline {
      position: relative;
      padding-left: 24px;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        bottom: 0;
        left: 8px;
        width: 2px;
        background-color: #eee;
      }

      .timeline-item {
        position: relative;
        padding-bottom: 24px;

        &:last-child {
          padding-bottom: 0;
        }

        .timeline-point {
          position: absolute;
          top: 0;
          left: -24px;
          width: 16px;
          height: 16px;
          border-radius: 50%;
          background-color: #eee;
          border: 2px solid #fff;

          &.pending {
            background-color: #FF9800;
          }

          &.processing {
            background-color: #2196F3;
          }

          &.completed {
            background-color: #4CAF50;
          }

          &.rejected {
            background-color: #F44336;
          }
        }

        .timeline-content {
          padding-left: 16px;

          .timeline-date {
            font-size: 14px;
            color: #999;
            margin-bottom: 4px;
          }

          .timeline-description {
            font-size: 14px;
            color: #333;
          }
        }
      }
    }
  }

  // 成功模态框内容
  .success-modal {
    .modal-body {
      text-align: center;

      .success-icon {
        font-size: 48px;
        color: #4CAF50;
        margin-bottom: 16px;
      }

      .success-message {
        font-size: 16px;
        color: #333;
        margin-bottom: 24px;
      }

      .success-detail {
        text-align: left;
        background-color: #f9f9f9;
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 24px;

        .detail-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 8px;

          &:last-child {
            margin-bottom: 0;
          }

          .label {
            color: #666;
          }

          .value {
            font-weight: 500;
            color: #333;

            &.address {
              font-family: 'Courier New', monospace;
              font-size: 14px;
              word-break: break-all;
            }
          }
        }
      }

      .close-success-btn {
        padding: 10px 24px;
        background-color: #4a6cf7;
        color: white;
        border: none;
        border-radius: 4px;
        font-size: 16px;
        cursor: pointer;
        transition: background-color 0.3s;

        &:hover {
          background-color: #3a5bd7;
        }
      }
    }
  }
}
</style>
